/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (C) 2012 Regents of the University of California
 */

#include <asm.h>
#include <csr.h>
#include <asm/sbidef.h>
#include <asm/sbiasm.h>

.section ".entry_function","ax"
ENTRY(_start)
  /* TODO: this is ther kernel''s entry point.
   * Same as head.S in Project 3?
   */
  csrw CSR_SIE, zero
  csrw CSR_SIP, zero

  /*
   *#Disable FPU to detect illegal usage of
   *#floating point in kernel space
   */
  li t0, SR_FS
  csrc sstatus, t0
  li t0, SR_SUM
  csrc sstatus, t0
  /*# Load the global pointer */
  .option push
  .option norelax
  la gp, __global_pointer$
  .option pop

  /*# Clear BSS for flat non-ELF images */
  csrr a0, CSR_MHARTID
  bnez a0, clear_bss_done
  
  la a3, __bss_start
  la a4, __BSS_END__
  ble a4, a3, clear_bss_done
clear_bss:
  sd zero, (a3)
  add a3, a3, RISCV_SZPTR
  blt a3, a4, clear_bss
clear_bss_done:
  csrr a0, CSR_MHARTID
  bnez a0, secondary
  la sp, cpu0_stack
  ld sp,0(sp)
  la tp, cpu0_pcb
  beqz a0, firstary
secondary:
  la sp, cpu1_stack
  ld sp,0(sp)
  la tp, cpu1_pcb
firstary:
  /*#setup C environment */
  
  csrw CSR_SSCRATCH, x0

  /* #this should never return */
  call main

loop:
  wfi
  j loop
END(_start)
